package com.netty.resolver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import com.netty.util.PackageUtil;

public final class ResourceResolver {

	public static InputStream getResource(String name) {
		String fileName = "com/netty/html" + name;
		return getInputStream(fileName);
	}

	public static InputStream getResourceJs(String name) {
		String fileName = "com/netty/js" + name;
		return getInputStream(fileName);
	}

	public static List<String> getResourceFile(String packageName) {
		try {
			List<String> packages = PackageUtil.getClassName(packageName);
			return packages;

		} catch (Exception e) {
			return null;
		}
	}

	public static void main(String atgs[]) {
		getResourceFile("com.netty.service");
	}

	public static InputStream getInputStream(String fileName) {
		System.out.println("+++++++  fileName为：" + fileName);
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		URL url = loader.getResource(fileName);
		if (url != null) {
			String type = url.getProtocol();
			System.out.println("+++++++   url 类型为： " + type + "----url 为：" + url);
			if ("file".equals(type)) {
				return ResourceResolver.class.getClassLoader().getResourceAsStream(fileName);
			} else if (("jar").equals(type)) {
				String[] jarInfo = url.getPath().split("!");
				String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/"));
				String packagePath = jarInfo[1].substring(1);
				try {
					JarFile jarFile = new JarFile(jarFilePath);
					Enumeration<JarEntry> entrys = jarFile.entries();
					while (entrys.hasMoreElements()) {
						JarEntry jarEntry = entrys.nextElement();
						String entryName = jarEntry.getName();
						if(entryName.equals(packagePath)){
							return jarFile.getInputStream(jarEntry);
						}
						
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

				return null;
			}
		}
		return null;
	}
}
